﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace QbservableCore.Serialization
{
    [DataContract]
    public class LambdaNode : ExpRepresentationBase
    {
        [DataMember]
        public ParameterNode[] Parameters { get; set; }
        
        [DataMember]
        public ExpRepresentationBase Body { get; set; }

        protected internal override Expression ToExpression(ExepressionBuilderCache exepressionBuilderCache)
        {
            ParameterExpression[] parameterExpressions = new ParameterExpression[Parameters.Length];
            for (int index = 0; index < Parameters.Length; index++)
            {
                parameterExpressions[index] = (ParameterExpression)Parameters[index].ToExpression(exepressionBuilderCache);
            }
            return Expression.Lambda(Body.ToExpression(exepressionBuilderCache), parameterExpressions);
        }

        protected override void TraverseChildren(Func<ExpRepresentationBase, ExpRepresentationBase> action)
        {
            TraverseNodes(Parameters, action);
            Body = Body.Traverse(action);
        }

        public override string ToString()
        {
            string parameters = string.Join(", ", Parameters.Cast<object>());
            return string.Format("({0})=> {1}", parameters, Body);
        }
    }
}